import React, {useState} from 'react';
import {useNavigate} from "react-router-dom";
import {Form, Input, Button, Checkbox, message} from 'antd';
import {LockOutlined, UserOutlined} from '@ant-design/icons';
import Md5 from 'js-md5';
import {postLogin} from "@/api/request/user.js";
import {getToken, setToken} from "@/util/token.js";
import '@/style/login.css'

const Login = () => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const getLocalStorageData = getToken()
    const fromData = {
        username: getLocalStorageData && getLocalStorageData.username,
        remember: getLocalStorageData && getLocalStorageData.remember,
    };

    const validatorLimit = (rule, value) => {
        if (rule.fullField === 'username') {
            if (!value) {
                return Promise.reject('用户名不能为空');
            } else if (!/^[a-zA-Z0-9]+$/.test(value)) {
                return Promise.reject('用户名只能包含字母和数字');
            }
            return Promise.resolve();
        }
        if (rule.fullField === 'password') {
            if (!value) {
                return Promise.reject('请输入密码');
            } else if (!/^[a-zA-Z0-9]+$/.test(value)) {
                return Promise.reject(new Error('密码只能包含字母和数字'));
            }
            return Promise.resolve();
        }
    }

    const onFinish = async (values) => {
        const {password, username, remember} = values;
        try {
            setLoading(true);
            const {data} = await postLogin({
                username: username,
                password: Md5(password),
            })
            setToken({
                username: remember ? username : '',
                token: data.access_token,
                remember: remember,
            });
            message.success("登录成功！");
            navigate('/home');
        } finally {
            setLoading(false);
        }
    }

    return (
        <div className='login-container'>
            <img src='http://java-admin.likeadmin.cn/adminapi/static/login_image.png'/>
            <div className='login-form'>
                <div className='login-form-title'>likeadmin开源</div>
                <Form onFinish={onFinish} autoComplete="off" style={{width: '100%'}} initialValues={fromData}
                      scrollToFirstError={{
                          behavior: 'instant', block: 'end', focus: true,
                      }}>
                    <Form.Item name="username" rules={[{validator: validatorLimit}]} validateTrigger={['onSubmit']}>
                        <Input addonBefore={<UserOutlined/>} size='small' placeholder="admin/user"/>
                    </Form.Item>

                    <Form.Item name="password" rules={[{validator: validatorLimit}]} validateTrigger={['onSubmit']}>
                        <Input addonBefore={<LockOutlined/>} size='small' type="password" placeholder="密码为123456"/>
                    </Form.Item>

                    <Form.Item name="remember" valuePropName="checked">
                        <Checkbox>记住账号</Checkbox>
                    </Form.Item>

                    <Form.Item>
                        <Button loading={loading} htmlType="submit" style={{width: '100%', height: '40px'}}
                                type="primary">登 录</Button>
                    </Form.Item>

                </Form>
            </div>
        </div>
    );
};

export default Login;